package com.ixuea.courses.mycloudmusicapisp.service;

import com.ixuea.courses.mycloudmusicapisp.domain.User;
import com.ixuea.courses.mycloudmusicapisp.mapper.UserMapper;
import com.ixuea.courses.mycloudmusicapisp.util.BCryptUtil;
import com.ixuea.courses.mycloudmusicapisp.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户session服务
 */
@Service
public class SessionService {

    /**
     * 用户Mapper
     */
    @Autowired
    private UserMapper mapper;

    /**
     * 保存session
     * @param data
     * @return
     */
    public boolean saveSession(User data) {
        return mapper.updateSessionDigest(data.getId(), data.getSessionDigest()) == Constant.RESULT_OK;
    }

    /**
     * 检查session
     * @param userId
     * @param authorization
     * @return
     */
    public User checkSession(String userId, String authorization) {
        //根据ID查询用户
        User data = mapper.find(userId);

        //判断用户是否存在
        if (data != null) {
            //判断session是否匹配
            if (BCryptUtil.matchEncode(authorization, data.getSessionDigest())) {
                return data;
            }
        }
        return null;
    }


    /**
     * 删除session
     * @param id
     * @return
     */
    public boolean deleteSession(String id) {
        return mapper.updateSessionDigest(id, null) == Constant.RESULT_OK;
    }
}
